const { logger } = require("../config/logConfig")
const Tags = require("../models/Tags")
const utils = require('../config/utils')
const sequelize = require("../config/database")
const { QueryTypes } = require("sequelize")
const Category = require("../models/category")
const { validationResult } = require("express-validator")
// 查询标签列表
async function tagsList (req, res) {
  let condition = utils.completeSelect(req.body)
  let pageObj = utils.pageSelect(req.body)
  try {
    const tags = await Tags.findAndCountAll({
      offset: pageObj.skip,
      limit: pageObj.limit,
      where: condition,
      order: [['createdAt', 'DESC']], // 根据创建时间倒序排序
      distinct: true,
      attributes: {
        exclude: ["createdAt", "updatedAt"],
      },
      include: [
        {
          model: Category,
          as: 'category'
        }
      ]
    })
    if (!tags) {
      utils.responseContent(res, 'OK', 200, data = { list: [], total: 0, pageSize: 10, pageNum: 1 })
    }
    let list = await Promise.all(tags.rows.map(async item => {
      return {
        id: item.id,
        name: item.name,
        category_id: item.category_id,
        category_name: item.category.category_name,
        del: item.del,
        rmk: item.rmk,
        stats: item.stats,
        ctime: item.ctime,
        mtime: item.mtime
      }
    }))
    utils.responseContent(res, 'OK', 200, data = {
      list: list,
      pageNum: (pageObj.skip / pageObj.limit) + 1,
      pageSize: pageObj.limit,
      total: tags.count
    })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ msg: '获取标签列表失败', code: 400 })
  }
}
/**
 * 新增
 * rmk:不用校验的请求参数
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
// 新增
async function tagsAdd (req, res) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    for (var i = 0; i < errors.array().length; i++) {
      return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
    }
  }
  const { name, category_id, rmk = '', stats } = req.body
  try {
    logger.info(req)
    const count = await Tags.count()
    let id
    if (count === 0) {
      // 如果是首次创建 则使用随机生成的 ID
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
      id = `1017${ randomNum }`
    } else {
      const [tag] = await sequelize.query(`SELECT Tags.id, Tags.category_id, Tags.stats, Tags.rmk, Tags.ctime, Tags.mtime FROM Tags JOIN Categories ON Categories.id =:category_id WHERE category_id =:category_id AND name= :name`, {
        type: QueryTypes.SELECT,
        replacements: {
          id: category_id,
          category_id,
          name
        }
      })
      if (tag) {
        return res.status(200).json({ msg: `${ name }的标签已经存在`, code: 500 })
      }
      // 获取第一条数据的ID，并在此基础上递增生成后续数据的 ID
      const maxIdTags = await Tags.findOne({ order: [['id', 'DESC']] })
      const maxId = parseInt(maxIdTags.id) // 获取最大ID的数值部分
      id = maxId + 1
    }
    await sequelize.query(
      `
      INSERT INTO Tags ( id, name, category_id, stats, rmk, ctime, mtime, createdAt, updatedAt )
      VALUES
        ( 
          :id,
          :name,
          :category_id,
          :stats,
          :rmk,
          :ctime,
          :mtime,
          NOW(),
          NOW()) 
        ON DUPLICATE KEY UPDATE id = id + 1;
    `,
      {
        type: QueryTypes.INSERT,
        replacements: {
          id: id,
          name,
          category_id: category_id,
          stats: stats,
          rmk: rmk,
          ctime: Date.now(),
          mtime: Date.now(),
        }
      }
    )
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: '新增标签失败', code: 500 })
  }
}

// 更新
async function tagsUpd (req, res) {
  const { id, name, category_id, rmk = '', stats } = req.body
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      for (var i = 0; i < errors.array().length; i++) {
        return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
      }
    }
    const [tag] = await sequelize.query(`SELECT name FROM Tags JOIN Categories ON Categories.id =:id WHERE category_id =:category_id AND name= :name`, {
      type: QueryTypes.SELECT,
      replacements: {
        id: category_id,
        category_id,
        name
      }
    })
    if (tag) {
      return res.status(200).json({ msg: `${ name }的标签已经存在`, code: 500 })
    }
    try {
      await sequelize.query(`
      UPDATE Tags SET
        name = :name,
        category_id = :category_id,
        stats = :stats,
        rmk = :rmk,
        mtime = :mtime,
        updatedAt = NOW()
      WHERE
        id = :id;
      `, {
        type: QueryTypes.INSERT,
        replacements: {
          id,
          name,
          category_id,
          rmk,
          stats,
          ctime: Date.now(),
          mtime: Date.now(),
        }
      })
      res.status(200).json({ msg: '更新成功', code: 0 })
    } catch (error) {
      logger.error(error)
      res.status(200).json({ msg: '更新标签失败', code: 500 })
    }
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: '编辑标签失败', code: 500 })
  }
}
// 获取详情
async function tagsDetail (req, res) {
  const { id } = req.query
  try {
    const [tag] = await sequelize.query(`SELECT id, name, category_id, stats, rmk FROM Tags WHERE id = :id`, {
      type: QueryTypes.SELECT,
      replacements: {
        id
      }
    })
    if (tag === null) {
      res.status(200).json({ msg: '查询标签失败', code: 0 })
    } else {
      res.status(200).json({ msg: 'OK', code: 0, data: tag })
    }
  } catch (error) {
    res.status(200).json({ msg: error, code: 0 })
  }
}
// 删除
async function tagsDele (req, res) {

}
async function isTagsExists (tagsId) {
  const tags = await Tags.findOne({ where: { id: tagsId } });
  return tags
}
module.exports = { tagsList, tagsAdd, tagsUpd, tagsDetail, tagsDele, isTagsExists }
